#!/usr/bin/env python
# -*- coding: utf-8 -*-

from models import Card, Node, dump_tree, init_engine
from sqlalchemy.ext.declarative import declarative_base
from sqlalchemy import create_engine
from sqlalchemy.orm import sessionmaker
import os
import csv

Base = declarative_base()

def import_from_csv(path, node):
    reader = csv.reader(open(path, 'rb'), delimiter=',', quotechar='"')
    for row in reader:
        node.cards.append(Card(unicode(row[0], 'utf-8'),\
                               unicode(row[1], 'utf-8'),\
                               unicode(row[2], 'utf-8'),\
                               node))

def import_dir(dir, node):
    print dir
    for name in os.listdir(dir):
        filename, ext = os.path.splitext(name)
        n = Node(unicode(filename, 'gb2312'))
        node.children.append(n)
        path = os.path.join(dir, name)
        
        if (os.path.isdir(path)):
            import_dir(path, n)
        elif (ext.lower() == ".csv"):
            import_from_csv(path, n)
    

if __name__ == '__main__':
    
    session = sessionmaker(init_engine(), expire_on_commit=False)()
    
    if (1):
        root = Node(u"English")
        import_dir('../data', root)
        session.add(root)
        session.commit()
    else:
        root = session.query(Node).\
               filter(Node.name == u"English").\
               first()
    
    dump_tree(root)
    
    